package qj.tool.logger;

import java.text.MessageFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import qj.util.StringUtil4;

public class LogPolicy {
	private static final Pattern PTN_PACKAGE = Pattern.compile("quanla\\.app\\.([^.]+).*");
	
	private static final MessageFormat MF_INFO 	= new MessageFormat("[{0,time,yy/MM/dd HH:mm:ss SSS}] {1} INFO  {2}");
	private static final MessageFormat MF_DEBUG = new MessageFormat("[{0,time,yy/MM/dd HH:mm:ss SSS}] {1} DEBUG {2}");
	private static final MessageFormat MF_ERROR	= new MessageFormat("[{0,time,yy/MM/dd HH:mm:ss SSS}] {1} ERROR {2}");
//	private static final MessageFormat MF_INFO 	= new MessageFormat("{1} - {2}");
//	private static final MessageFormat MF_DEBUG = new MessageFormat("{1} - {2}");
//	private static final MessageFormat MF_ERROR	= new MessageFormat("{1} - {2}");
	private Class oclass;

	private final boolean showConsole;
	
	private LogPolicy(Class oclass, boolean showConsole) {
		this.oclass = oclass;
		this.showConsole = showConsole;
	}
	
	public boolean needAppendFile() {
		return PTN_PACKAGE.matcher(oclass.getPackage().getName()).matches();
	}

	public String getLogFile() {
		Matcher matcher = PTN_PACKAGE.matcher(oclass.getPackage().getName());
		matcher.matches();
		return "C:/temp/log/quan/" + matcher.group(1) + ".log";
	}

	public String formatInfoContent(String content) {
		if (StringUtil4.isMutiLine(content))
			content = "\n" + content;
		return MF_INFO.format(new Object[] {new Date(), StringUtil4.ensureLengthLeft(getClassMethod(), 32) , content});
	}

	public String formatDebugContent(String content) {
		if (StringUtil4.isMutiLine(content))
			content = "\n" + content;
		return MF_DEBUG.format(new Object[] {new Date(), StringUtil4.ensureLengthLeft(getClassMethod(), 32) , content});
	}

	public String formatErrorContent(String content) {
		if (StringUtil4.isMutiLine(content))
			content = "\n" + content;
		return MF_ERROR.format(new Object[] {new Date(), StringUtil4.ensureLengthLeft(getClassMethod(), 32) , content});
	}

	public static LogPolicy getInstance(Class oclass2, boolean showConsole) {
		return new LogPolicy(oclass2, showConsole);
	}

	private String getClassMethod() {
		StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
		StackTraceElement ele = stackTrace[3];
		String className = ele.getClassName();
		return className.substring(className.lastIndexOf('.') + 1) + "." + ele.getMethodName();
	}

	public boolean isShowConsole() {
		return showConsole;
	}
}
